﻿using System;
using System.Linq;
using System.ComponentModel;
using System.Windows.Data;
using System.Collections.ObjectModel;

using Microsoft.Practices.Prism.ViewModel;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Events;
using Microsoft.Practices.Prism.Regions;

using SystemModule.Models;
using SystemModule.Services;
using ServiceAgent;
using Infrastructure;
using Infrastructure.Helpers;
using Infrastructure.Events;
using System.Windows.Input;
using System.Windows;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Prism.Interactivity.InteractionRequest;
using SystemModule.Views;
using ServiceAgent.StudentService;
using System.Collections.Generic;
using ServiceAgent.CatalogueService;
using ServiceAgent.SystemService;

namespace SystemModule.ViewModels
{
    /// <summary>
    /// ViewModel for NhomNguoiDungDetailView.
    /// </summary>
    public class NhomNguoiDungDetailViewModel : NotificationObject, INavigationAware
    {
        #region Fields
        private IRegionNavigationService navigationService;
        private IEventAggregator eventAggregator;

        private readonly IUnityContainer container;
        private IRegionManager regionManager;

        int uid;

        ServiceAgent.CatalogueService.DonViDTO donVi;

        ObservableCollection<QuyenDTO> quyenList;
        ObservableCollection<QuyenDTO> quyenDonViList = new ObservableCollection<QuyenDTO>();
        private ObservableCollection<QuyenDTO> oldQuyenDonViList;

        #endregion

        #region Constructor
        /// <summary>
        /// Default constructor.
        /// </summary>
        public NhomNguoiDungDetailViewModel(IEventAggregator eventAggregator, IRegionManager regionManager, IUnityContainer container)
        {
            this.eventAggregator = eventAggregator;
            this.regionManager = regionManager;
            this.container = container;

            this.Initialize();
        }
        #endregion

        #region Administrative Properties
        public ServiceAgent.CatalogueService.DonViDTO DonVi
        {
            get { return donVi; }
            set
            {
                donVi = value;
                RaisePropertyChanged(() => this.DonVi);
            }
        }

        public ObservableCollection<QuyenDTO> QuyenList
        {
            get { return quyenList; }
            set
            {
                quyenList = value;
                RaisePropertyChanged(() => this.QuyenList);
            }
        }

        public ObservableCollection<QuyenDTO> QuyenDonViList
        {
            get { return quyenDonViList; }
            set
            {
                quyenDonViList = value;
                RaisePropertyChanged(() => this.QuyenDonViList);
            }
        }
        #endregion

        #region Command Properties
        public DelegateCommand<object> GoBackCommand { get; private set; }
        public ICommand SaveCommand { get; private set; }
        #endregion

        #region Private Methods
        private void Initialize()
        {
            this.GoBackCommand = new DelegateCommand<object>(GoBack, CanGoBack);
            this.SaveCommand = new DelegateCommand(this.OnRaiseSave);
        }

        void GetDonVi(int id)
        {
            try
            {
                using (var proxy = container.Resolve<CatalogueServiceAgent>())
                {
                    DonVi = proxy.GetDonViByID(id);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Có lỗi xảy ra");
            }
        }

        void GetQuyenList(int id)
        {
            try
            {
                using (var proxy = container.Resolve<SystemServiceAgent>())
                {
                    QuyenList = proxy.GetQuyenNotYetByDonViID(id);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Có lỗi xảy ra");
            }
        }

        void GetQuyenDonViList(int id)
        {
            try
            {
                using (var proxy = container.Resolve<SystemServiceAgent>())
                {
                    oldQuyenDonViList = proxy.GetQuyenByDonViID(id);
                }
                foreach (var quyen in oldQuyenDonViList)
                {
                    quyenDonViList.Add(quyen);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Có lỗi xảy ra");
            }
        }

        private void OnRaiseSave()
        {
            try
            {
                using (var proxy = container.Resolve<CatalogueServiceAgent>())
                {
                    proxy.SaveDonVi(DonVi);
                }

                var toRemove = oldQuyenDonViList.Except(quyenDonViList);
                var toAdd = quyenDonViList.Except(oldQuyenDonViList);

                if (toAdd.Count() > 0)
                {
                    using (var proxy = container.Resolve<SystemServiceAgent>())
                    {
                        proxy.SetQuyenListForDonVi(uid, new ObservableCollection<QuyenDTO>(toAdd));
                    }
                }

                if (toRemove.Count() > 0)
                {
                    using (var proxy = container.Resolve<SystemServiceAgent>())
                    {
                        proxy.UnSetQuyenListForDonVi(uid, new ObservableCollection<QuyenDTO>(toRemove));
                    }
                }
                oldQuyenDonViList = quyenDonViList;
                MessageBox.Show("Lưu lại thành công");
            }
            catch (Exception)
            {
                MessageBox.Show("Có lỗi xảy ra");
            }
        }

        private void GoBack(object commandArg)
        {
            if (navigationService.Journal.CanGoBack)
            {
                navigationService.Journal.GoBack();
            }
        }

        private bool CanGoBack(object commandArg)
        {
            return navigationService.Journal.CanGoBack;
        }
        #endregion

        #region INavigationAware Members
        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            // Called to see if this view can handle the navigation request.
            // If it can, this view is activated.
            return false;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {

            // Called when this view is deactivated as a result of navigation to another view.
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            //// Called to initialize this view during navigation.

            // getting a reference to navigation service:
            if (navigationService == null)
                navigationService = navigationContext.NavigationService;

            //// Retrieve any required paramaters from the navigation Uri.
            string id = navigationContext.Parameters["ID"];
            if (!string.IsNullOrEmpty(id))
            {
                this.uid = Convert.ToInt32(id);
            }

            this.GetDonVi(uid);
            this.GetQuyenList(uid);
            this.GetQuyenDonViList(uid);
        }
        #endregion
    }
}
